<template>
  <a-modal
    title="新建"
    :width="840"
    :visible="visible"
    :confirmLoading="loading"
    @ok="modalOk"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-row>
          <a-col :span="12">
            <a-form-item label="报刊种类">
              <a-select v-decorator="['pressType', {rules: [{required: true, message: '请输入报刊种类！'}], initialValue: model.pressType}]">
                <a-select-option v-for="(item, index) in settingList" :key="index" :value="item.id">{{ item.title }}</a-select-option>
                <!-- <a-select-option value="温州日报">温州日报</a-select-option>
                <a-select-option value="温州晚报">温州晚报</a-select-option>
                <a-select-option value="温州都市报">温州都市报</a-select-option>
                <a-select-option value="温州商报">温州商报</a-select-option>
                <a-select-option value="科技金融时报">科技金融时报</a-select-option> -->
              </a-select>
              <!-- <a-input v-decorator="['pressType', {rules: [{required: true, message: '请输入报刊种类！'}], initialValue: model.pressType}]" /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收订员">
              <a-input style="cursor: pointer;" @click="selectPeople" v-decorator="['subScriptioner', {rules: [{required: true, message: '请输入收订员！'}], initialValue: model.subScriptioner}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="份数">
              <a-input v-decorator="['subscriptionCount', {rules: [{required: true, message: '请输入份数！'}], initialValue: model.subscriptionCount}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="手机号">
              <a-input v-decorator="['cellPhone', {rules: [{required: true, message: '请输入手机号！'}], initialValue: model.cellPhone}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="地址" :labelCol="{span: 4, offset: 0}" :wrapperCol="{span: 18}">
              <!-- :not-found-content="fetching ? undefined : null" -->
              <a-select
                show-search
                :value="matchSelectValue"
                placeholder="小区/大厦/街道名称"
                style="width: 100%"
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @search="onMatchSelectSearch"
                @change="onMatchSelectChange"
                v-decorator="['detailedAddress', {rules: [{required: true, message: '请输入地址！'}], initialValue: model.detailedAddress}]"
              >
                <!-- <a-spin v-if="fetching" slot="notFoundContent" size="small" /> -->
                <a-select-option v-for="(item, index) in searchList" :key="index">
                  {{ item.roadName }}
                  <p style="font-size: 14px !important; color: #666 !important;">
                    门牌范围：{{ item.houseNumber }}  {{ item.flagStr }}
                  </p>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="门牌号">
              <a-input v-decorator="['doorplate', {rules: [{required: true, message: '请输入门牌号！'}], initialValue: model.doorplate}]" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="详细地址">
              <a-input v-decorator="['detailedAddress', {rules: [{required: true, message: '请输入详细地址！'}], initialValue: model.detailedAddress}]" />
            </a-form-item>
          </a-col> -->
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="投递站">
              <div style="display: flex;justify-content: center;align-items: center;">
                <a-select
                  style="flex:1;"
                  v-decorator="['deliverStation', {rules: [{required: true, message: '请选择投递站！'}], initialValue: model.deliverStation}]"
                >
                  <a-select-option
                    :key="index"
                    :value="item.id + ''"
                    v-for="(item, index) in deliveryList"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <!-- <a-button type="primary" size="small" @click="toMatchDelivery">选择</a-button> -->
              </div>

              <!-- <a-input  /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="投递段">
              <a-select
                v-decorator="['deliverPart', {rules: [{required: true, message: '请选择投递段！'}], initialValue: model.deliverPart }]"
              >
                <a-select-option
                  :key="index"
                  :value="item.id + ''"
                  v-for="(item, index) in deliveryDetailList"
                >
                  {{ item.roadName }} - {{ item.houseNumber }}
                </a-select-option>
              </a-select>
              <!-- <a-input v-decorator="['deliverPart', {rules: [{required: true, message: '请输入投递段！'}], initialValue: model.deliverPart}]" /> -->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="开始时间">
              <a-date-picker show-time v-decorator="['startDate', {rules: [{ type: 'object', required: true, message: '请输入开始时间'}], initialValue: model.startDate}]" />
              <!-- <a-date-picker v-decorator="['startDate', {rules: [{ type: 'object', required: true, message: 'Please select time!' }]}]" style="width: 100%" /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间">
              <a-date-picker show-time v-decorator="['endDate', {rules: [{ type: 'object', required: true, message: '请输入结束时间'}], initialValue: model.endDate}]" />
              <!-- <a-input v-decorator="['endDate', {rules: [{required: true, message: '请输入结束时间'}], initialValue: model.endDate}]" /> -->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="审核状态">
              <a-select
                placeholder="审核状态"
                disabled
                v-decorator="['SubmitState', {rules: [{required: true, message: '请选择审核状态！'}], initialValue: model.submitState || '待审核'}]"
              >
                <a-select-option value="待审核">待审核</a-select-option>
                <a-select-option value="待开票">待开票</a-select-option>
                <a-select-option value="待发行">待发行</a-select-option>
                <a-select-option value="已完成">已完成</a-select-option>
              </a-select>
              <!-- <a-input v-decorator="['submitState', {rules: [{required: true, message: '请选择审核状态！'}], initialValue: model.submitState}]" /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户名称">
              <a-input v-decorator="['member', {rules: [{required: true, message: '请选择客户名称'}], initialValue: model.member && model.member.name}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="关联客户">
              <a-select
                v-decorator="['customerName', {rules: [{required: true, message: '请选择关联客户'}], initialValue: model.customerName}]"
              >
                <a-select-option
                  :key="index"
                  :value="item.name"
                  v-for="(item, index) in customerList"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <!-- <a-input  /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="金额合计">
              <a-input :disabled="true" :value="totalPrice" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :row-key="(record)=>record.id"
        :showPagination="true"
      >

      </s-table> -->
    </a-spin>
    <select-people @OnSelect="OnSelect" :visible="selectVisible" :model="this.model" @cancel="()=>{this.selectVisible=false}" @ok="modalOk" />
    <match-delivery @OnSelect="OnMatchDeliverySelect" :visible="matchDeliveryVisible" :model="this.model" @cancel="()=>{this.matchDeliveryVisible=false}" @ok="modalOk" />
    <!-- <select-people /> -->
  </a-modal>
</template>

<script>
// 审核状态 0=待审核 1=待开票 2=待发行 3=已完成
import pick from 'lodash.pick'
import { addDeliveries, putDeliveries, getMemberLists, getCustomerLists, getDeliveryLists, getDeliveryDetailLists, getStationRecord, getSettingLists, getCurrentUser } from '@/api/manage'
import { STable } from '@/components'
import SelectPeople from './SelectPeople'
import MatchDelivery from './MatchDelivery'
const fields = ['id']

export default {
  name: 'MemberForm',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    }
    return {
      nowSelectMatch: {},
      matchSelectValue: '',
      searchList: [],
      matchDeliveryVisible: false,
      settingList: [],
      selectVisible: false,
      form: this.$form.createForm(this),
      totalPrice: 0.00,
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '发票流水号',
          dataIndex: 'record.fpqqlsh'
        },
        {
          title: '发票审核状态',
          dataIndex: 'record.submitState'
        },
        {
          title: '发票金额',
          dataIndex: 'record.totalPrice'
        }
      ],
      loadData: (parameter) => {
        return getStationRecord({ deliveryId: this.model.id }).then(res => {
          this.totalPrice = 0.00
          res.data.forEach((item) => {
            this.totalPrice += item.record.totalPrice
          })
          return {
            data: res.data,
            totalCount: parseInt(res.headers['x-count']),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          }
        })
      },
      memberList: [],
      customerList: [],
      deliveryList: [],
      deliveryDetailList: []
    }
  },
  components: {
    STable,
    SelectPeople,
    MatchDelivery
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    const _self = this
    this.$watch('model', () => {
      this.form = this.$form.createForm(this)
      if (this.visible) {
        getDeliveryDetailLists().then(res => {
          this.deliveryDetailList = res.data
        })
        getCurrentUser().then(_res => {
          getSettingLists().then(res => {
          // getSettingLists({ departmentId: _res.data.department.id }).then(res => {
            this.settingList = res.data
          })
        })
        getDeliveryLists().then(res => {
          this.deliveryList = res.data
        })
        getCustomerLists().then(res => {
          this.customerList = res.data
        })
        getMemberLists().then(res => {
          this.memberList = res.data
        })
        _self.$nextTick(() => {
          this.model && this.form.setFieldsValue(pick(this.model, fields))
          // this.$refs.table.refresh(true)
        })
      }
    })
  },
  methods: {
    onMatchSelectSearch (value) {
      getDeliveryDetailLists({ search: value }).then(res => {
        this.form.setFieldsValue({
          'detailedAddress': ''
        })
        this.searchList = res.data
        res.data.forEach(item => {
          const tempArr = item.houseNumber.split('-')
          const flag = (parseInt(tempArr[0]) <= 0)
          item.flagStr = ''
          if ((!flag && tempArr[1] % 2 === 0) && tempArr.length > 1) {
            item.flagStr = '双数'
          } else if ((!flag && tempArr[1] % 2 !== 0) && tempArr.length > 1) {
            item.flagStr = '单数'
          }
        })
      }).catch(e => {
        console.error(e)
      })
    },
    onMatchSelectChange (value) {
      this.matchSelectValue = this.searchList[value].roadName
      this.nowSelectMatch = this.searchList[value]
      this.form.setFieldsValue({
        'deliverPart': this.nowSelectMatch.deliveryStation.deliveryPart,
        'deliverStation': this.nowSelectMatch.deliveryStation.name
      })
    },
    OnMatchDeliverySelect (record) {
      this.form.setFieldsValue({
        'deliverPart': record.deliveryStation.deliveryPart,
        'deliverStation': record.deliveryStation.name
      })
      this.matchDeliveryVisible = false
    },
    toMatchDelivery () {
      this.matchDeliveryVisible = true
    },
    selectPeople () {
      this.selectVisible = true
    },
    OnSelect (member) {
      this.selectVisible = false
      this.model && this.form.setFieldsValue({
        'subScriptioner': member.name,
        'cellPhone': member.cellPhone
      })
      // this.model.member = member.name
    },
    modalOk () {
      this.form.validateFieldsAndScroll((errors, values) => {
        if (!errors) {
          delete values.id
          if (this.matchSelectValue !== '') values.detailedAddress = this.matchSelectValue
          if (this.model && this.model.id) {
            putDeliveries(this.model.id, values).then(res => {
              this.$emit('ok')
            })
          } else {
            addDeliveries(values).then(res => {
              this.$emit('ok')
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
